package cn.xiaoyu.su.util;

import cn.xiaoyu.su.enums.BizCodeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author sufs
 * @date 2022/10/27 11:21
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JsonData {

    private int code;

    private Object data;

    private String message;

    /**
     * 获取远程调用数据
     * 注意事项：
     * 支持多单词下划线转驼峰（序列化和反序列化）
     *
     * @param typeReference
     * @param <T>
     * @return
     */
    public <T> T getData(TypeReference<T> typeReference) {
        return JSON.parseObject(JSON.toJSONString(data),typeReference);
    }

    public static JsonData buildSuccess() {
        return new JsonData(0,null,"");
    }

    public static JsonData buildSuccess(Object data) {
        return new JsonData(0,data,"");
    }

    public static JsonData buildError(String message) {
        return new JsonData(-1,null,message);
    }

    public static JsonData buildCodeAndMsg(int code, String msg) {
        return new JsonData(code,null,msg);
    }

    public static JsonData buildResult(BizCodeEnum bizCodeEnum) {
        return buildCodeAndMsg(bizCodeEnum.getCode(),bizCodeEnum.getMessage());
    }

}
